package com.mstore.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import com.mstore.pojo.Account;
import com.mstore.pojo.BaseMember;
import com.mstore.pojo.BgiveRule;
import com.mstore.pojo.Consume;
import com.mstore.pojo.EnterpriseIntegralRule;
import com.mstore.pojo.ExamineSetting;
import com.mstore.pojo.Member;
import com.mstore.pojo.Score;
import com.mstore.pojo.Shop;
import com.mstore.pojo.User;
import com.mstore.service.AccountService;
import com.mstore.service.BaseMemberService;
import com.mstore.service.BgiveRuleService;
import com.mstore.service.ConsumeService;
import com.mstore.service.EnterpriseIntegralRuleService;
import com.mstore.service.ExamineSettingService;
import com.mstore.service.LogConsumeExamineService;
import com.mstore.service.MemberService;
import com.mstore.service.ScoreService;
import com.mstore.service.ShopService;
import com.mstore.util.CalendarUtil;

/**
 * 为杭州晓荷公司定制开发的付账功能
 */
public class LogConsumeExamineAction extends BaseAction implements SessionAware {

	private static final long serialVersionUID = -8054234485888283734L;

	/**
	 * 晓荷公司id
	 */
	public static final Long xiaoheAccountId = 81L;

	private Map<String, Object> session;

	private String result;

	private LogConsumeExamineService logConsumeExamineService;

	private ShopService shopService;

	private AccountService accountService;

	private BgiveRuleService bGiveRuleService;

	private MemberService memberService;

	private ConsumeService consumeService;

	private ExamineSettingService examineSettingService;

	private ScoreService scoreService;

	private BaseMemberService baseMemberService;

	private EnterpriseIntegralRuleService enterpriseIntegralRuleService;

	private Consume consume;

	private Member member;

	private BaseMember baseMember;

	private Shop shop;

	private List<Shop> shops;

	private Double money;

	/**
	 * 判断是否使用会员余额交易
	 */
	private int type;

	private static Logger logger = Logger
			.getLogger(LogConsumeExamineAction.class.getName());

	private List<ExamineSetting> examineSettings;

	private ExamineSetting examineSetting;

	private List<Consume> consumes;

	/**
	 * 当前页
	 */
	private int index;

	/**
	 * 总页数
	 */
	private int page;

	/**
	 * 包含查询条件的Consume封装类 用于在action之间传递查询条件
	 */
	private Consume consumeWithCondition;

	/**
	 * 年销售额
	 */
	private double yearConsume;

	/**
	 * 月销售额
	 */
	private double monthConsume;

	/**
	 * 日销售额
	 */
	private double dayConsume;

	/**
	 * 店铺名称
	 */
	private String shopName;

	/**
	 * 计时器
	 */
	private static Timer timer;

	/**
	 * 分店登陆 验证晓荷公司操作员身份
	 */
	public String verifyLoginFromUser() {
		Object uObj = session.get("user");
		if (uObj == null) {
			result = "系统异常";
			return "error";
		}

		User user = (User) uObj;
		Shop shop = new Shop();
		shop.setId(user.getShopId());
		shop = shopService.getShopById(shop);
		if (shop != null) {
			if (shop.getEaId().longValue() == xiaoheAccountId.longValue()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("temp", "yes");
				result = mapTojson(map);
			}
			else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("temp", "no");
				result = mapTojson(map);
			}
		}

		return "verifyFinish";
	}

	/**
	 * 管理员登陆 验证晓荷公司管理员身份
	 */
	public String verifyLoginFromAccount() {
		Object uObj = session.get("account");
		if (uObj == null) {
			result = "系统异常";
			return "error";
		}

		Account account = (Account) uObj;
		if (account.getId().longValue() == xiaoheAccountId.longValue()) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "yes");
			result = mapTojson(map);
		}
		else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "no");
			result = mapTojson(map);
		}

		return "verifyFinish";
	}

	/**
	 * 购物结算
	 */
	public String shopping() {
		try {
			Object object = session.get("user");
			if (object == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			if (this.member == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			if (this.shop == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			if (this.money == null) {
				result = "未填写消费金额";
				return "error";
			}

			if (this.consume == null) {
				result = "未填写小票号";
				return "error";
			}

			User user = (User) object;

			this.shop = shopService.getShopById(this.shop);
			if (this.shop == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			Account account = new Account();
			account.setId(this.shop.getEaId());
			account = accountService.findAccountById(account);
			if (account == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			this.member = memberService.getMemberById(this.member);
			if (this.member == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			// 添加消费记录
			addConsume(account, this.shop, user, this.member, type);

			return "shopping";
		}
		catch (Exception e) {
			logger.error("杭州晓荷购物结算报错", e);
		}

		return NONE;
	}

	/**
	 * 进入消费审核设定页面 如果已设置了消费审核规则，则跳转到查看页面 如果没有设置，则跳转到新建页面
	 */
	public String goToExamineSetting() {
		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		Account account = (Account) object;

		String temp = NONE;
		boolean isSetting = examineSettingService.isSetting(account.getId());
		if (isSetting)
			// 已经设定了消费审核规则
			temp = "goToWatch";
		else
			temp = "goToAdd";

		return temp;
	}

	/**
	 * 查看消费审核规则
	 */
	public String watchExamineSetting() {
		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		Account account = (Account) object;

		if (examineSetting == null)
			examineSetting = new ExamineSetting();

		examineSetting.setEaId(account.getId());
		examineSetting = examineSettingService
				.getExamineSettingByCondition(examineSetting);

		return "watchExamineSetting";
	}

	/**
	 * 添加消费审核规则
	 */
	public String addExamineSetting() {
		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getDailyMoneyLimit() == null) {
			result = "未填写每日自动审核金额上限！";
			return "error";
		}

		if (StringUtils.isBlank(examineSetting.getExamineBegintime())) {
			result = "未填写审核起始时间！";
			return "error";
		}

		if (examineSetting.getExamineInterval() == null) {
			result = "未填写自动审核间隔时长！";
			return "error";
		}

		Account account = (Account) object;
		examineSetting.setEaId(account.getId());
		examineSetting.setExamineStart(1); // 启动

		examineSettingService.addExamineSetting(examineSetting);

		// 启动定时器
		stopTimer();
		startTimer(examineSetting.getExamineBegintime(),
				examineSetting.getExamineInterval());

		return SUCCESS;
	}

	/**
	 * 跳转到修改消费审核规则页面
	 */
	public String goToUpdateExamineSetting() {
		if (examineSetting == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getId() == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		examineSetting = examineSettingService
				.getExamineSettingByCondition(examineSetting);

		return "goToUpdate";
	}

	/**
	 * 修改消费审核规则
	 */
	public String updateExamineSetting() {
		if (examineSetting == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getDailyMoneyLimit() == null) {
			result = "未填写每日自动审核金额上限！";
			return "error";
		}

		if (StringUtils.isBlank(examineSetting.getExamineBegintime())) {
			result = "未填写审核起始时间！";
			return "error";
		}

		if (examineSetting.getExamineInterval() == null) {
			result = "未填写自动审核间隔时长！";
			return "error";
		}

		examineSettingService.updateExamineSetting(examineSetting);

		examineSetting = examineSettingService
				.getExamineSettingByCondition(examineSetting);

		if (examineSetting != null) {
			// 如果自动审核开关设定为启动
			// 重启定时器
			if (examineSetting.getExamineStart() == 1) {
				stopTimer();
				startTimer(examineSetting.getExamineBegintime(),
						examineSetting.getExamineInterval());
			}
		}

		return SUCCESS;
	}

	/**
	 * 修改自动审核状态
	 */
	public String modifyExamineStart() {
		if (examineSetting == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getId() == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getExamineStart() == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		examineSettingService.updateExamineSetting(examineSetting);

		examineSetting = examineSettingService
				.getExamineSettingByCondition(examineSetting);

		if (examineSetting != null) {
			// 如果自动审核开关设定为启动
			// 重启定时器
			if (examineSetting.getExamineStart() == 1) {
				stopTimer();
				startTimer(examineSetting.getExamineBegintime(),
						examineSetting.getExamineInterval());
			}
			else {
				stopTimer();
			}
		}

		return SUCCESS;
	}

	/**
	 * 删除消费审核规则
	 */
	public String delExamineSetting() {
		if (examineSetting == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (examineSetting.getId() == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		examineSettingService.delExamineSetting(examineSetting);

		// 停止定时器
		stopTimer();

		return SUCCESS;
	}

	/**
	 * 人工审核查询
	 */
	public String watchManualExamine() {
		Object object = session.get("account");
		if (object == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		Account account = (Account) object;
		Long eaId = account.getId();

		if (consume == null) {
			consume = new Consume();
		}
		consume.setEaId(eaId);

		int pagetemp = examineSettingService
				.getCountConsumesByCondition(consume);
		settingPageAndIndex(pagetemp);

		consumes = examineSettingService.getPageConsumesByCondition(index,
				consume);

		shop = new Shop();
		shop.setEaId(eaId);
		shops = shopService.getAllShop(shop);

		Long shopId = consume.getShopId();
		// 今日销售额
		Consume con = new Consume();
		con.setEaId(xiaoheAccountId);
		con.setShopId(shopId);
		con.setBeginTime(CalendarUtil.formatDate(CalendarUtil.getTodayDate()));
		con.setEndTime(CalendarUtil.formatDate(CalendarUtil.getTodayDate())
				+ " 23:59:59");
		dayConsume = examineSettingService.getSumConsumesByCondition(con);

		// 获取店铺名
		if (shopId == null || shopId == 0) {
			shopName = "全体店铺";
		}
		else {
			shop.setId(shopId);
			shop = shopService.getShopById(shop);
			if (shop != null) {
				shopName = shop.getName();
			}
		}

		return "watchManualExamine";
	}

	/**
	 * 人工消费审核
	 */
	public String manualExamine() {
		if (consume == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		if (consume.getId() == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}

		List<Consume> consumelist = examineSettingService
				.getConsumesByCondition(consume);

		if (consumelist.isEmpty()) {
			return "examineFinish";
		}

		consume = consumelist.get(0);
		// 修改消费记录审核标示
		consume.setExamineFlag(1); // 批准通过
		examineSettingService.modifyConsumeExamineFlag(consume);

		// 添加积分记录
		Score score = addScore(consume);

		Long eaId = score.getEaId();
		Long memberId = score.getMemberId();
		Double numer = score.getNumer();
		// 判断是否是企业会员
		// 如果是，更新会员信息
		// 如果不是，添加成为新会员
		BaseMember baseMember = baseMemberService
				.getOneBaseMemberByMemberIdAndEaId(memberId, eaId);
		if (baseMember == null) {
			// 添加新会员
			baseMember = new BaseMember();
			baseMember.setCreateTime(getCreateTime());
			baseMember.setEaId(eaId);
			baseMember.setMemberId(memberId);
			baseMember.setBalance(0d);
			baseMember.setScore(numer);
			baseMember.setLevel(getMemberLevelname(eaId, numer.intValue()));

			baseMemberService.save(baseMember);
		}
		else {
			// 更新原有数据
			int baseScore = baseMember.getScore().intValue();
			try {
				String level = getMemberLevelname(eaId,
						baseScore + numer.intValue());
				baseMember.setLevel(level);
				baseMember.setScore(baseScore + numer);

				baseMemberService.updateBaseMember(baseMember);
			}
			catch (Exception e) {
				logger.error("更新会员等级报错", e);
			}
		}

		return "examineFinish";
	}

	/**
	 * 验证自动审核启动时间是否失效
	 */
	public String verifyExamineBegintime() {
		try {
			ExamineSetting examineSetting = new ExamineSetting();
			examineSetting.setEaId(xiaoheAccountId);
			examineSetting = examineSettingService
					.getExamineSettingByCondition(examineSetting);
			Map<String, Object> map = new HashMap<String, Object>();
			if (examineSetting != null) {
				Date date1 = CalendarUtil.textParseToDate(
						examineSetting.getExamineBegintime(),
						"yyyy-MM-dd HH:mm:ss");
				Date date2 = CalendarUtil.getTodayDate();
				if (date1.getTime() < date2.getTime()) {
					// 自动审核启动时间已失效
					map.put("temp", "自动审核启动时间已失效，请修改后再启动！");
					result = mapTojson(map);
				}
				else {
					map.put("temp", "ok");
					result = mapTojson(map);
				}
			}
		}
		catch (Exception e) {
			logger.error("验证自动审核启动时间是否失效报错", e);
		}

		return "verifyFinish";
	}

	/**
	 * 查询消费记录
	 */
	public String watchConsumeLogByPage() {
		try {
			Object object = session.get("account");
			if (object == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}

			if (consume == null) {
				consume = new Consume();
			}
			consume.setEaId(xiaoheAccountId);
			consume.setExamineFlag(1); // 只查询审核通过的记录

			int pagetemp = examineSettingService
					.getCountConsumesByCondition(consume);
			settingPageAndIndex(pagetemp);
			consumes = examineSettingService.getPageConsumesByCondition(index,
					consume);

			// 计算年销售额
			Consume con = new Consume();
			con.setEaId(xiaoheAccountId);
			con.setExamineFlag(1);
			String beginTime = CalendarUtil.formatDate(CalendarUtil
					.getCurrYearFirst());
			String endTime = CalendarUtil.formatDate(CalendarUtil
					.getCurrYearLast()) + " 23:59:59";
			con.setBeginTime(beginTime);
			con.setEndTime(endTime);
			yearConsume = examineSettingService.getSumConsumesByCondition(con);

			// 计算月销售额
			beginTime = CalendarUtil.formatDate(CalendarUtil
					.getCurrMonthFirst());
			endTime = CalendarUtil.formatDate(CalendarUtil.getCurrMonthLast())
					+ " 23:59:59";
			con.setBeginTime(beginTime);
			con.setEndTime(endTime);
			monthConsume = examineSettingService.getSumConsumesByCondition(con);

			// 计算日销售额
			beginTime = CalendarUtil.formatDate(CalendarUtil.getTodayDate());
			endTime = CalendarUtil.formatDate(CalendarUtil.getTodayDate())
					+ " 23:59:59";
			con.setBeginTime(beginTime);
			con.setEndTime(endTime);
			dayConsume = examineSettingService.getSumConsumesByCondition(con);

			// 查询所有店铺
			shop = new Shop();
			shop.setEaId(xiaoheAccountId);
			shops = shopService.getAllShopByEaId(shop);
		}
		catch (Exception e) {
			logger.error("晓荷贸易查询消费记录报错", e);
		}

		return "getConsumeLogByPage";
	}

	/**
	 * 一键审核，对账金额验证
	 */
	public String verifyConsumeLog() {
		Map<String, Object> map = new HashMap<String, Object>();
		if (consume == null) {
			map.put("temp", "验证失败");
			result = mapTojson(map);
			return "verifyFinish";
		}

		Double verifyMoney = consume.getVerifyMoney();
		if (verifyMoney == null) {
			map.put("temp", "验证失败");
			result = mapTojson(map);
			return "verifyFinish";
		}

		String shopName = null;
		Long shopId = consume.getShopId();
		if (shopId == null || shopId == 0) {
			shopName = "全体店铺";
		}
		else {
			shop = new Shop();
			shop.setId(shopId);
			shop = shopService.getShopById(shop);
			shopName = (shop != null ? shop.getName() : "");
		}

		// 审核金额条件
		// 企业、店铺、当日
		consume.setEaId(xiaoheAccountId);
		consume.setBeginTime(CalendarUtil.formatDate(CalendarUtil
				.getTodayDate()));
		consume.setEndTime(CalendarUtil.formatDate(CalendarUtil.getTodayDate())
				+ " 23:59:59");
		Double consumeMoney = examineSettingService
				.getSumConsumesByCondition(consume);

		if (verifyMoney.doubleValue() >= consumeMoney) {
			map.put("temp", "ok");
			result = mapTojson(map);
		}
		else {
			map.put("temp", "【" + shopName + "】今日的消费总金额大于您所填写的验证金额，请您核查消费记录！");
			result = mapTojson(map);
		}

		return "verifyFinish";
	}

	/**
	 * 执行一键审核
	 */
	public String executeClickExamine() {
		if (consume == null) {
			consume = new Consume();
		}
		consume.setEaId(xiaoheAccountId);
		consume.setExamineFlag(0);
		String todayDate = CalendarUtil.formatDate(CalendarUtil.getTodayDate());
		String beginTime = todayDate + " 00:00:00";
		String endTime = todayDate + " 23:59:59";
		consume.setBeginTime(beginTime);
		consume.setEndTime(endTime);

		List<Consume> consumes = logConsumeExamineService
				.getLogConsumeExamineByCondition(consume);

		Score score;
		BaseMember baseMember;
		Long eaId;
		Long memberId;
		Double numer;

		for (Consume consumeExamine : consumes) {
			// 修改消费记录审核标示
			consumeExamine.setExamineFlag(1); // 批准通过
			examineSettingService.modifyConsumeExamineFlag(consumeExamine);

			// 添加积分记录
			score = addScore(consumeExamine);
			if (score == null) {
				continue;
			}

			eaId = score.getEaId();
			memberId = score.getMemberId();
			numer = score.getNumer();
			// 判断是否是企业会员
			// 如果是，更新会员信息
			// 如果不是，添加成为新会员
			baseMember = baseMemberService.getOneBaseMemberByMemberIdAndEaId(
					memberId, eaId);
			if (baseMember == null) {
				// 添加新会员
				baseMember = new BaseMember();
				baseMember.setCreateTime(getCreateTime());
				baseMember.setEaId(eaId);
				baseMember.setMemberId(memberId);
				baseMember.setBalance(0d);
				baseMember.setScore(numer);
				baseMember.setLevel(getMemberLevelname(eaId, numer.intValue()));

				baseMemberService.save(baseMember);
			}
			else {
				// 更新原有数据
				int baseScore = baseMember.getScore().intValue();
				String level = getMemberLevelname(eaId,
						baseScore + numer.intValue());
				baseMember.setLevel(level);
				baseMember.setScore(baseScore + numer);

				baseMemberService.updateBaseMember(baseMember);
			}
		}

		return "executeFinish";
	}

	/**
	 * 验证小票号的唯一性
	 */
	public String verifySmallBanks() {
		Map<String, Object> map = new HashMap<String, Object>();
		if (consume == null) {
			map.put("message", "小票号验证失败！");
			result = mapTojson(map);
			return "verifyFinish";
		}

		String smallBanks = consume.getSmallBanks();
		if (StringUtils.isBlank(smallBanks)) {
			map.put("message", "小票号验证失败！");
			result = mapTojson(map);
			return "verifyFinish";
		}

		consume.setEaId(xiaoheAccountId);

		int count = logConsumeExamineService.getCountSmallBanks(consume);
		if (count > 0) {
			map.put("message", "此小票号已经使用过了！");
			result = mapTojson(map);
		}
		else {
			map.put("message", "ok");
			result = mapTojson(map);
		}

		return "verifyFinish";
	}

	/**
	 * 添加消费记录
	 * 
	 * @param shopmark
	 * @param dateTime
	 */
	private void addConsume(Account account, Shop shop, User user,
			Member member, int shopmark) {
		// 企业名称
		consume.setEaName(account.getName());
		// 店铺名称
		consume.setShopName(shop.getName());
		// 操作员名称
		consume.setUserName(user.getUserName());
		// 会员名称
		consume.setMemberName(StringUtils.isBlank(member.getName()) ? ""
				: member.getName());
		// 会员手机号
		consume.setMemberMobile(member.getMobile());

		consume.setEaId(account.getId());
		consume.setShopId(shop.getId());
		consume.setUserId(user.getId());
		consume.setMemberId(member.getId());

		consume.setCreateTime(getCreateTime());
		consume.setMoney((this.money));
		consume.setType(shopmark);
		consume.setExamineFlag(0); // 初始设为不通过，等待审核
		consumeService.addConsume(consume);
	}

	/**
	 * * 添加积分记录
	 */
	private Score addScore(Consume consume) {
		Long eaId = consume.getEaId();
		Score score = new Score();

		score.setEaId(eaId);
		score.setShopId(consume.getShopId());
		score.setUserId(consume.getUserId());
		score.setMemberId(consume.getMemberId());

		score.setEaName(consume.getEaName());
		score.setShopName(consume.getShopName());
		score.setUserName(consume.getUserName());
		score.setMemberName(consume.getMemberName());

		score.setType(1);
		score.setCreateTime(consume.getCreateTime());

		int moneyToScore = (int) consume.getMoney();
		score.setNumer(countBaseMemberSorce(eaId, moneyToScore));

		scoreService.addScore(score);

		return score;
	}

	/**
	 * * 计算该次消费获取的积分
	 */
	private int countBaseMemberSorce(Long eaId, int score) {
		BgiveRule rule = bGiveRuleService.getGiveRuleByTime(getCreateTime(),
				eaId);
		if (rule == null) {
			return score;
		}
		else {
			int type = rule.getType();
			if (type == 2) {
				return (int) (score * rule.getRaiseValue());
			}
			else if (type == 3) {
				return score + rule.getRaiseValue().intValue();
			}
			else {
				return score;
			}
		}
	}

	/**
	 * 获取积分会员等级
	 */
	private String getMemberLevelname(Long eaId, int score) {
		String levelName = "";

		EnterpriseIntegralRule integralRule = new EnterpriseIntegralRule();
		integralRule.setEaId(eaId);
		List<EnterpriseIntegralRule> integralRules = enterpriseIntegralRuleService
				.watchEnterpriseIntegralRule(integralRule);

		for (int i = 0; i < integralRules.size(); i++) {
			if (score >= integralRules.get(i).getMinValue()
					&& score < integralRules.get(i).getMaxValue()) {
				levelName = integralRules.get(i).getName();
				break;
			}
			if (i == integralRules.size() - 1) {
				if (score >= integralRules.get(i).getMaxValue()) {
					levelName = integralRules.get(i).getName();
				}
			}
		}

		return levelName;
	}

	/**
	 * 自动审核
	 */
	private void autoExamine() {
		Consume consume = new Consume();
		consume.setEaId(xiaoheAccountId);
		consume.setExamineFlag(0);
		String todayDate = CalendarUtil.formatDate(CalendarUtil.getTodayDate());
		String beginTime = todayDate + " 00:00:00";
		String endTime = todayDate + " 23:59:59";
		consume.setBeginTime(beginTime);
		consume.setEndTime(endTime);

		ExamineSetting examineSetting = new ExamineSetting();
		examineSetting.setEaId(xiaoheAccountId);
		examineSetting = examineSettingService
				.getExamineSettingByCondition(examineSetting);

		if (examineSetting != null) {
			Double sumMoney = logConsumeExamineService
					.getSumMoneyByCondition(consume);
			// 当天总消费金额小于设定的自动审核消费金额上限
			if (sumMoney.doubleValue() <= examineSetting.getDailyMoneyLimit()
					.doubleValue()) {
				List<Consume> consumes = logConsumeExamineService
						.getLogConsumeExamineByCondition(consume);

				Score score;
				BaseMember baseMember;
				Long eaId;
				Long memberId;
				Double numer;

				for (Consume consumeExamine : consumes) {
					// 修改消费记录审核标示
					consumeExamine.setExamineFlag(1); // 批准通过
					examineSettingService
							.modifyConsumeExamineFlag(consumeExamine);

					// 添加积分记录
					score = addScore(consumeExamine);
					if (score == null) {
						continue;
					}

					eaId = score.getEaId();
					memberId = score.getMemberId();
					numer = score.getNumer();
					// 判断是否是企业会员
					// 如果是，更新会员信息
					// 如果不是，添加成为新会员
					baseMember = baseMemberService
							.getOneBaseMemberByMemberIdAndEaId(memberId, eaId);
					if (baseMember == null) {
						// 添加新会员
						baseMember = new BaseMember();
						baseMember.setCreateTime(getCreateTime());
						baseMember.setEaId(eaId);
						baseMember.setMemberId(memberId);
						baseMember.setBalance(0d);
						baseMember.setScore(numer);
						baseMember.setLevel(getMemberLevelname(eaId,
								numer.intValue()));

						baseMemberService.save(baseMember);
					}
					else {
						// 更新原有数据
						int baseScore = baseMember.getScore().intValue();
						String level = getMemberLevelname(eaId, baseScore
								+ numer.intValue());
						baseMember.setLevel(level);
						baseMember.setScore(baseScore + numer);

						baseMemberService.updateBaseMember(baseMember);
					}
				}
			}
		}
	}

	/**
	 * * 启动自动审核定时器
	 */
	private void startTimer(String startTime, Integer interval) {
		try {
			// 参数处理
			Date beginTime = CalendarUtil.textParseToDate(startTime,
					"yyyy-MM-dd HH:mm:ss");
			long mInterval = 1000 * 60 * interval;

			// 启动
			if (timer == null) {
				timer = new Timer();
			}
			timer.scheduleAtFixedRate(new TimerTask() {

				@Override
				public void run() {
					autoExamine();
				}
			}, beginTime, mInterval);
		}
		catch (Exception e) {
			logger.error("文本时间格式解析报错", e);
		}
	}

	/**
	 * 停止计时器
	 */
	private void stopTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	/**
	 * 设置当前页和总页数
	 */
	private void settingPageAndIndex(int pagetemp) {
		if (pagetemp == 0) {
			pagetemp = 1;
		}
		if (pagetemp % 14 == 0) {
			page = pagetemp / 14;
		}
		else {
			page = (pagetemp / 14) + 1;
		}
		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}
	}

	public LogConsumeExamineService getLogConsumeExamineService() {
		return logConsumeExamineService;
	}

	public void setLogConsumeExamineService(
			LogConsumeExamineService logConsumeExamineService) {
		this.logConsumeExamineService = logConsumeExamineService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public ShopService getShopService() {
		return shopService;
	}

	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	public AccountService getAccountService() {
		return accountService;
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	public Consume getConsume() {
		return consume;
	}

	public void setConsume(Consume consume) {
		this.consume = consume;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public BgiveRuleService getbGiveRuleService() {
		return bGiveRuleService;
	}

	public void setbGiveRuleService(BgiveRuleService bGiveRuleService) {
		this.bGiveRuleService = bGiveRuleService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public ConsumeService getConsumeService() {
		return consumeService;
	}

	public void setConsumeService(ConsumeService consumeService) {
		this.consumeService = consumeService;
	}

	public ExamineSettingService getExamineSettingService() {
		return examineSettingService;
	}

	public void setExamineSettingService(
			ExamineSettingService examineSettingService) {
		this.examineSettingService = examineSettingService;
	}

	public List<ExamineSetting> getExamineSettings() {
		return examineSettings;
	}

	public void setExamineSettings(List<ExamineSetting> examineSettings) {
		this.examineSettings = examineSettings;
	}

	public ExamineSetting getExamineSetting() {
		return examineSetting;
	}

	public void setExamineSetting(ExamineSetting examineSetting) {
		this.examineSetting = examineSetting;
	}

	public List<Consume> getConsumes() {
		return consumes;
	}

	public void setConsumes(List<Consume> consumes) {
		this.consumes = consumes;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public List<Shop> getShops() {
		return shops;
	}

	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public ScoreService getScoreService() {
		return scoreService;
	}

	public void setScoreService(ScoreService scoreService) {
		this.scoreService = scoreService;
	}

	public BaseMemberService getBaseMemberService() {
		return baseMemberService;
	}

	public void setBaseMemberService(BaseMemberService baseMemberService) {
		this.baseMemberService = baseMemberService;
	}

	public EnterpriseIntegralRuleService getEnterpriseIntegralRuleService() {
		return enterpriseIntegralRuleService;
	}

	public void setEnterpriseIntegralRuleService(
			EnterpriseIntegralRuleService enterpriseIntegralRuleService) {
		this.enterpriseIntegralRuleService = enterpriseIntegralRuleService;
	}

	public BaseMember getBaseMember() {
		return baseMember;
	}

	public void setBaseMember(BaseMember baseMember) {
		this.baseMember = baseMember;
	}

	public Consume getConsumeWithCondition() {
		return consumeWithCondition;
	}

	public void setConsumeWithCondition(Consume consumeWithCondition) {
		this.consumeWithCondition = consumeWithCondition;
	}

	public double getYearConsume() {
		return yearConsume;
	}

	public void setYearConsume(double yearConsume) {
		this.yearConsume = yearConsume;
	}

	public double getMonthConsume() {
		return monthConsume;
	}

	public void setMonthConsume(double monthConsume) {
		this.monthConsume = monthConsume;
	}

	public double getDayConsume() {
		return dayConsume;
	}

	public void setDayConsume(double dayConsume) {
		this.dayConsume = dayConsume;
	}

	public String getShopName() {
		return shopName;
	}

	public void setShopName(String shopName) {
		this.shopName = shopName;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
